import { get, post, $delete, patch, getFile } from './http.js'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Base64 } from 'js-base64'
import { ServerConfig } from '@/common/config.js'

function toBlob(base64str: string, filetype: string) {
  const bytes = window.atob(base64str)
  let n = bytes.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bytes.charCodeAt(n)
  }
  return new Blob([u8arr], { type: filetype })
}
const startLoading = function () {
  return ElLoading.service({
    lock: true,
    text: '加载中' + '...',
    spinner: 'el-icon-ElLoading',
    background: 'rgba(255, 255, 255, 0.1)'
  })
}
/**
 * 查询操作
 * @param {Object} url
 */
export const query = function (url: string, isloading = true) {
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    get(url)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          resolve(data.data.result.data)
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 翻页查询操作，返回的结构格式为resolse(data,curPage,totalPage,totalRow)
 * @param {Object} url
 * @param {Object} limit
 * @param {Object} page
 */
export const queryByPage = function (url: string, limit = 10, page = 1, isloading = true) {
  let link = ''
  if (url.indexOf('?') > 0) {
    link = url + '&limit=' + limit + '&page=' + page
  } else {
    link = url + '?limit=' + limit + '&page=' + page
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    get(link)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          resolve({
            QueryDatas: data.data.result.data.QueryDatas,
            CurrentPage: data.data.result.data.CurrentPage,
            TotalPage: data.data.result.data.TotalPage,
            TotalRow: data.data.result.data.TotalRow
          })
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 发送请求操作
 * @param {Object} url
 * @param {Object} data
 * @param {Object} sendMethod 请求方法:post,patch,delete
 */
export const send = function (url: string, data: any, sendMethod = 'post', isloading = true) {
  return new Promise((resolve, reject) => {
    if (sendMethod.toLowerCase() === 'post') {
      const ElLoading = isloading ? startLoading() : null
      post(url, data)
        .then((data: any) => {
          if (ElLoading) ElLoading.close()
          if (data.data.result.code === 'success') {
            if (data.data.result.data) {
              resolve(data.data.result.data)
            } else {
              resolve(null)
            }
            ElMessage({
              message: data.data.result.msg ? data.data.result.msg : '操作成功',
              type: 'success'
            })
          } else {
            ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
              confirmButtonText: '确定'
            })
            reject(data.data.result.msg)
          }
        })
        .catch((error) => {
          if (ElLoading) ElLoading.close()
          ElMessage({
            message: error,
            type: 'error'
          })
          reject(error)
          console.error(error)
        })
    } else if (sendMethod === 'patch') {
      const ElLoading = isloading ? startLoading() : null
      patch(url, data)
        .then((data: any) => {
          if (ElLoading) ElLoading.close()
          if (data.data.result.code === 'success') {
            if (data.data.result.data) {
              resolve(data.data.result.data)
            } else {
              resolve(null)
            }
            ElMessage({
              message: data.data.result.msg ? data.data.result.msg : '操作成功',
              type: 'success'
            })
          } else {
            ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
              confirmButtonText: '确定'
            })
            reject(data.data.result.msg)
          }
        })
        .catch((error) => {
          if (ElLoading) ElLoading.close()
          ElMessage({
            message: error,
            type: 'error'
          })
          reject(error)
          console.error(error)
        })
    } else if (sendMethod === 'delete') {
      const ElLoading = isloading ? startLoading() : null
      $delete(url, { data: data })
        .then((data: any) => {
          if (ElLoading) ElLoading.close()
          if (data.data.result.code === 'success') {
            resolve(null)
            ElMessage({
              message: data.data.result.msg ? data.data.result.msg : '操作成功',
              type: 'success'
            })
          } else {
            ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
              confirmButtonText: '确定'
            })
            reject(data.data.result.msg)
          }
        })
        .catch((error) => {
          if (ElLoading) ElLoading.close()
          ElMessage({
            message: error,
            type: 'error'
          })
          reject(error)
          console.error(error)
        })
    } else {
      console.error('不支持' + sendMethod + '请求')
    }
  })
}
/**
 * 上传文件到文件服务
 * @param {*} file 文件对象
 * @param {*} onProgress 进度事件,格式：onProgress(percentage)
 * @returns
 */
export const uploadStream2FileService = function (
  file: any,
  onProgress: (percentage: number) => void,
  isloading = true
) {
  const formData = new FormData()
  formData.append('file', file)
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    axios({
      url: ServerConfig.IMG_UPLOAD_URL + '/fileset/upload_stream',
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-databoundary = ' + new Date().getTime()
      },
      data: formData,
      onUploadProgress: (ProgressEvent: any) => {
        if (ProgressEvent.lengthComputable) {
          const currentPer =
            parseInt(((ProgressEvent.loaded / ProgressEvent.total) * 10000).toString()) / 100
          const currentPercentage = currentPer > 100 ? 100 : currentPer
          if (onProgress) onProgress(currentPercentage)
        }
      }
    })
      .then((data) => {
        if (ElLoading) ElLoading.close()
        const dataResult = data.data.result
        if (dataResult.code === 'success') {
          ElMessage({
            message: '上传成功',
            type: 'success'
          })
          resolve(dataResult)
        } else {
          ElMessageBox.alert('上传失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(dataResult.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 回收文件
 * @param {*} file 文件uid或文件url
 * @param {*} access_key "访问Key，值存在则该文件要访问必须使用key才可以
 * @returns
 */
export const recycle2FileService = function (file: any, access_key = '', isloading = true) {
  let uid = ''
  if (typeof file === 'string') {
    const arr = file.split('/')
    uid = arr[arr.length - 1]
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    axios({
      url: ServerConfig.IMG_UPLOAD_URL + '/fileset/recycle/' + uid,
      method: 'patch',
      data: {
        access_key: access_key
      }
    })
      .then((data) => {
        if (ElLoading) ElLoading.close()
        const dataResult = data.data.result
        if (dataResult.code === 'success') {
          ElMessage({
            message: dataResult.msg ? dataResult.msg : '操作成功',
            type: 'success'
          })
          resolve(dataResult)
        } else {
          ElMessageBox.alert('请求失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(dataResult.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 恢复文件
 * @param {*} file 文件uid或文件url
 * @param {*} access_key "访问Key，值存在则该文件要访问必须使用key才可以
 * @returns
 */
export const recover2FileService = function (file: any, access_key = '', isloading = true) {
  let uid = ''
  if (typeof file === 'string') {
    const arr = file.split('/')
    uid = arr[arr.length - 1]
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    axios({
      url: ServerConfig.IMG_UPLOAD_URL + '/fileset/recover/' + uid,
      method: 'patch',
      data: {
        access_key: access_key
      }
    })
      .then((data) => {
        if (ElLoading) ElLoading.close()
        const dataResult = data.data.result
        if (dataResult.code === 'success') {
          ElMessage({
            message: dataResult.msg ? dataResult.msg : '操作成功',
            type: 'success'
          })
          resolve(dataResult)
        } else {
          ElMessageBox.alert('请求失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(dataResult.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 恢复文件
 * @param {*} file 文件uid或文件url
 * @param {*} access_key "访问Key，值存在则该文件要访问必须使用key才可以
 * @returns
 */
export const delete2FileService = function (file: any, access_key = '', isloading = true) {
  let uid = ''
  if (typeof file === 'string') {
    const arr = file.split('/')
    uid = arr[arr.length - 1]
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    axios({
      url: ServerConfig.IMG_UPLOAD_URL + '/fileset/' + uid,
      method: 'delete',
      data: {
        access_key: access_key
      }
    })
      .then((data) => {
        if (ElLoading) ElLoading.close()
        const dataResult = data.data.result
        if (dataResult.code === 'success') {
          ElMessage({
            message: dataResult.msg ? dataResult.msg : '操作成功',
            type: 'success'
          })
          resolve(dataResult)
        } else {
          ElMessageBox.alert('请求失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(dataResult.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 从文件服务器上下载文件
 * @param {*} fileUrl
 * @param {string} filename
 */
export const downloadFromFileService = function (fileUrl: string, filename: string) {
  let downUrl = ''
  if (fileUrl.indexOf('/name/') !== -1) {
    downUrl = fileUrl.slice(0, fileUrl.indexOf('/name/'))
  } else {
    downUrl = fileUrl
  }
  const url = new URL(downUrl)
  let newfileurl = ServerConfig.IMG_UPLOAD_URL + url.pathname + url.search
  newfileurl = newfileurl.replace('/dl', '')
  // 创建隐藏的可下载链接
  const eleLink = document.createElement('a')
  eleLink.download = filename
  eleLink.style.display = 'none'
  // 字符内容转变成地址
  eleLink.href = newfileurl
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}
/**
 * 获取动态表单事件列表
 */
export const getEvents4DForm = function (isloading = true) {
  return query('/events4dform', isloading)
}
/**
 * 执行动态表单的事件
 * @param {*} event_no 事件编号
 * @param {*} this_data 页面上当前编辑的行/页面资料
 * @param {*} parameters 参数集合(包含querystring，post，path参数)
 * @returns Promise
 */
export const excuteDFormEvent = function (
  event_no: string,
  this_data: any,
  parameters = {},
  isloading = true
) {
  return send(
    '/events4dform/' + event_no + '/eval',
    {
      this_data: btoa(encodeURIComponent(JSON.stringify(this_data))),
      parameters: parameters
    },
    'post',
    isloading
  )
}
/**
 * 获取元数据列表
 * @param {boolean} inc_fc 是否包含固定栏位
 * @returns 元数据列表
 */
export const getMetaData = function (inc_fc: boolean, isloading = true) {
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    get('/metadata?inc_fc=' + inc_fc)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.status === 200 && data.data.result) {
          resolve(data.data.result)
        } else {
          ElMessageBox.alert('操作失败:' + data.data.error, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 获取词典表列表
 * @returns 词典表列表
 */
export const getDictionary = function (isloading = true) {
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    get('/dictionarytable')
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.status === 200 && data.data.result) {
          resolve(data.data.result)
        } else {
          ElMessageBox.alert('操作失败:' + data.data.error, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 获取元数据和词典表列表
 * @returns 列表
 */
export const getAllSchema = function (isloading = true) {
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    get('/metadata/alltableschema')
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              data: data.data.result.data
            })
          } else {
            resolve([])
          }
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单查询
 * @param {object} options 参数对象
 */
export const mdFormQuery = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    limit: 10,
    page: 1,
    parent_pk: '',
    filter_column: '',
    filter_value: '',
    query_columns: '',
    fixed_filter_express: '',
    fixed_orderby_express: '',
    other_condition_express: ''
  }
  Object.assign(default_options, options)
  if (default_options.fixed_filter_express) {
    if (typeof default_options.fixed_filter_express === 'string') {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(default_options.fixed_filter_express)
      )
    } else {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_filter_express))
      )
    }
  }
  if (default_options.fixed_orderby_express) {
    if (typeof default_options.fixed_orderby_express === 'string') {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(default_options.fixed_orderby_express)
      )
    } else {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_orderby_express))
      )
    }
  }
  if (default_options.other_condition_express) {
    if (typeof default_options.other_condition_express === 'string') {
      default_options.other_condition_express = Base64.encode(
        encodeURIComponent(default_options.other_condition_express)
      )
    } else {
      default_options.other_condition_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.other_condition_express))
      )
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    post('/md_form/' + default_options.id + '/query', default_options)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              page: data.data.result.page,
              limit: data.data.result.limit,
              total_page: data.data.result.total_page,
              total_count: data.data.result.total_count,
              data: data.data.result.data
            })
          } else {
            resolve(null)
          }
          // ElMessage({
          //   message: data.data.result.msg ? data.data.result.msg : '操作成功',
          //   type: 'success'
          // })
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单Pop栏位查询
 * @param {object} options 参数对象
 */
export const mdFormQueryPop = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    limit: 10,
    page: 1,
    filter: '',
    is_filter_deleted: true,
    column_name: '',
    fixed_filter_express: '',
    fixed_orderby_express: '',
    other_condition_express: '',
    this_data: '',
    ref_data: ''
  }
  Object.assign(default_options, options)
  if (default_options.fixed_filter_express) {
    if (typeof default_options.fixed_filter_express === 'string') {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(default_options.fixed_filter_express)
      )
    } else {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_filter_express))
      )
    }
  }
  if (default_options.fixed_orderby_express) {
    if (typeof default_options.fixed_orderby_express === 'string') {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(default_options.fixed_orderby_express)
      )
    } else {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_orderby_express))
      )
    }
  }
  if (default_options.other_condition_express) {
    if (typeof default_options.other_condition_express === 'string') {
      default_options.other_condition_express = Base64.encode(
        encodeURIComponent(default_options.other_condition_express)
      )
    } else {
      default_options.other_condition_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.other_condition_express))
      )
    }
  }
  if (default_options.this_data) {
    if (typeof default_options.this_data === 'string') {
      default_options.this_data = Base64.encode(encodeURIComponent(default_options.this_data))
    } else {
      default_options.this_data = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.this_data))
      )
    }
  }
  if (default_options.ref_data) {
    if (typeof default_options.ref_data === 'string') {
      default_options.ref_data = Base64.encode(encodeURIComponent(default_options.ref_data))
    } else {
      default_options.ref_data = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.ref_data))
      )
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    patch('/md_form/pop/' + default_options.id + '/' + default_options.column_name, default_options)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              page: data.data.result.page,
              limit: data.data.result.limit,
              total_page: data.data.result.total_page,
              total_count: data.data.result.total_count,
              data: data.data.result.data,
              column_value: data.data.result.column_value,
              column_show: data.data.result.column_show,
              column_text: data.data.result.column_text
            })
          } else {
            resolve(null)
          }
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单新增
 * @param {object} options 参数对象
 */
export const mdFormInsert = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    data: {},
    fixed_data_express: {}
  }
  Object.assign(default_options, options)
  if (default_options.fixed_data_express) {
    if (typeof default_options.fixed_data_express === 'string') {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(default_options.fixed_data_express)
      )
    } else {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_data_express))
      )
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    let url = ''
    if (Array.isArray(default_options.data)) {
      url = '/md_form'
    } else {
      url = '/md_form/' + default_options.id
    }
    post(url, default_options)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve(data.data.result.data)
          } else {
            resolve(null)
          }
          ElMessage({
            message: data.data.result.msg ? data.data.result.msg : '操作成功',
            type: 'success'
          })
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单修改
 * @param {object} options 参数对象
 */
export const mdFormUpdate = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    data: {
      _default_pk: ''
    },
    fixed_data_express: {}
  }
  Object.assign(default_options, options)
  if (default_options.fixed_data_express) {
    if (typeof default_options.fixed_data_express === 'string') {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(default_options.fixed_data_express)
      )
    } else {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_data_express))
      )
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    let url = ''
    if (Array.isArray(default_options.data)) {
      url = '/md_form/' + default_options.id
    } else {
      url = '/md_form/' + default_options.id + '/' + default_options.data._default_pk
    }
    patch(url, default_options)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve(data.data.result.data)
          } else {
            resolve(null)
          }
          ElMessage({
            message: data.data.result.msg ? data.data.result.msg : '操作成功',
            type: 'success'
          })
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单删除
 * @param {*} meta_uid 元数据表uid
 * @param {*} pkOrArray pk或pk的array
 */
export const mdFormDelete = function (meta_uid: string, pkOrArray: any, isloading = true) {
  const default_options = {
    data: [] as Array<any>
  }
  let data = [] as Array<any>
  if (Array.isArray(pkOrArray)) {
    data = pkOrArray as Array<any>
  } else {
    const arr = pkOrArray.split(',')
    data = arr
  }
  default_options.data = data
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    const url = '/md_form/' + meta_uid
    $delete(url, { data: default_options })
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve(data.data.result.data)
          } else {
            resolve(null)
          }
          ElMessage({
            message: data.data.result.msg ? data.data.result.msg : '操作成功',
            type: 'success'
          })
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单逻辑操作
 * @param {object} options 参数对象
 */
export const mdFormLogicOperation = function (options: any, op: string, isloading = true) {
  const default_options = {
    id: '',
    pk: '',
    fixed_filter_express: {},
    fixed_data_express: {}
  }
  Object.assign(default_options, options)
  if (default_options.fixed_filter_express) {
    if (typeof default_options.fixed_filter_express === 'string') {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(default_options.fixed_filter_express)
      )
    } else {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_filter_express))
      )
    }
  }
  if (default_options.fixed_data_express) {
    if (typeof default_options.fixed_data_express === 'string') {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(default_options.fixed_data_express)
      )
    } else {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_data_express))
      )
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    let url = '/md_form/{id}/{pk}/{op}'
    url = url
      .replace('{id}', default_options.id)
      .replace('{pk}', default_options.pk)
      .replace('{op}', op)
    patch(url, default_options)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve(data.data.result.data)
          } else {
            resolve(null)
          }
          ElMessage({
            message: data.data.result.msg ? data.data.result.msg : '操作成功',
            type: 'success'
          })
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单保存(增改删)
 * @param {object} options 参数对象
 */
export const mdFormSave = function (options = {}, isloading = true) {
  const default_options: any = {
    id: '',
    data: {},
    deletedData: null,
    fixed_data_express: ''
  }
  Object.assign(default_options, options)
  if (default_options.fixed_data_express) {
    if (typeof default_options.fixed_data_express === 'string') {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(default_options.fixed_data_express)
      )
    } else {
      default_options.fixed_data_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_data_express))
      )
    }
  }
  let deleted_pks: string[] = []
  if (default_options.deletedData) {
    if (typeof default_options.deletedData === 'string') {
      const arr = default_options.deletedData.split(',')
      deleted_pks = arr
    } else if (Array.isArray(default_options.deletedData)) {
      default_options.deletedData.forEach((item: any) => {
        if (typeof item === 'string') {
          deleted_pks.push(item)
        } else if (item['_default_pk']) {
          deleted_pks.push(item['_default_pk'])
        }
      })
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    let url = '/md_form/{id}/save'
    url = url.replace('{id}', default_options.id)
    if (default_options.data && default_options.data.length > 0) {
      post(url, {
        id: default_options.id,
        data: default_options.data,
        fixed_data_express: default_options.fixed_data_express
      })
        .then((data: any) => {
          if (data.data.result.code === 'success') {
            if (deleted_pks && deleted_pks.length > 0) {
              $delete('/md_form/' + default_options.id, {
                data: {
                  data: deleted_pks
                }
              })
                .then((data2: any) => {
                  if (ElLoading) ElLoading.close()
                  if (data2.data.result.code === 'success') {
                    // 返回保存的结果
                    if (data.data.result.data) {
                      resolve(data.data.result.data)
                    } else {
                      resolve(null)
                    }
                    ElMessage({
                      message: data.data.result.msg ? data.data.result.msg : '操作成功',
                      type: 'success'
                    })
                  } else {
                    ElMessageBox.alert('操作失败:' + data2.data.result.msg, '出错了', {
                      confirmButtonText: '确定'
                    })
                    reject(data2.data.result.msg)
                  }
                })
                .catch((error) => {
                  if (ElLoading) ElLoading.close()
                  ElMessage({
                    message: error,
                    type: 'error'
                  })
                  reject(error)
                  console.error(error)
                })
            } else {
              if (ElLoading) ElLoading.close()
              if (data.data.result.data) {
                resolve(data.data.result.data)
              } else {
                resolve(null)
              }
              ElMessage({
                message: data.data.result.msg ? data.data.result.msg : '操作成功',
                type: 'success'
              })
            }
          } else {
            if (ElLoading) ElLoading.close()
            ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
              confirmButtonText: '确定'
            })
            reject(data.data.result.msg)
          }
        })
        .catch((error) => {
          if (ElLoading) ElLoading.close()
          ElMessage({
            message: error,
            type: 'error'
          })
          reject(error)
          console.error(error)
        })
    } else if (deleted_pks && deleted_pks.length > 0) {
      $delete('/md_form/' + default_options.id, {
        data: {
          data: deleted_pks
        }
      })
        .then((data2: any) => {
          if (ElLoading) ElLoading.close()
          if (data2.data.result.code === 'success') {
            resolve(null)
            ElMessage({
              message: data2.data.result.msg ? data2.data.result.msg : '操作成功',
              type: 'success'
            })
          } else {
            ElMessageBox.alert('操作失败:' + data2.data.result.msg, '出错了', {
              confirmButtonText: '确定'
            })
            reject(data2.data.result.msg)
          }
        })
        .catch((error) => {
          if (ElLoading) ElLoading.close()
          ElMessage({
            message: error,
            type: 'error'
          })
          reject(error)
          console.error(error)
        })
    }
  })
}
/**
 * 动态表单获取级联主从表
 * @param {object} options 参数对象
 */
export const mdFormCadecaseMSSelect = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    column_name: '',
    is_filter_deleted: true,
    parent_pk: '',
    parent_level: 0,
    start_meta_name: '',
    start_level_column: '',
    start_level_value: ''
  }
  Object.assign(default_options, options)
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    post(
      '/md_form/cadecase_ms/' + default_options.id + '/' + default_options.column_name,
      default_options
    )
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              is_last_level: data.data.result.is_last_level,
              data: data.data.result.data
            })
          } else {
            resolve(null)
          }
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 根据值获取获取主从表级联的text
 * @param {object} options 参数对象
 */
export const getMDFormCadecaseMSText = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    column_name: '',
    is_filter_deleted: true,
    value: ''
  }
  Object.assign(default_options, options)
  if (Array.isArray(default_options.value)) {
    default_options.value = default_options.value.join(',')
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    post(
      '/md_form/cadecase_ms/' + default_options.id + '/' + default_options.column_name + '/text',
      default_options
    )
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              data: data.data.result.data
            })
          } else {
            resolve(null)
          }
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单获取级联树表
 * @param {object} options 参数对象
 */
export const mdFormCadecaseTreeSelect = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    column_name: '',
    is_filter_deleted: true,
    parent_pk: '',
    parent_level: 0,
    start_meta_name: '',
    start_level_column: '',
    start_level_value: '',
    fixed_orderby_express: '',
    this_data: '',
    ref_data: ''
  }
  Object.assign(default_options, options)
  if (default_options.fixed_orderby_express) {
    if (typeof default_options.fixed_orderby_express === 'string') {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(default_options.fixed_orderby_express)
      )
    } else {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_orderby_express))
      )
    }
  }
  if (default_options.this_data) {
    if (typeof default_options.this_data === 'string') {
      default_options.this_data = Base64.encode(encodeURIComponent(default_options.this_data))
    } else {
      default_options.this_data = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.this_data))
      )
    }
  }
  if (default_options.ref_data) {
    if (typeof default_options.ref_data === 'string') {
      default_options.ref_data = Base64.encode(encodeURIComponent(default_options.ref_data))
    } else {
      default_options.ref_data = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.ref_data))
      )
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    post(
      '/md_form/cadecase_tree/' + default_options.id + '/' + default_options.column_name,
      default_options
    )
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              data: data.data.result.data
            })
          } else {
            resolve(null)
          }
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 根据值获取获取树表表级联的text
 * @param {object} options 参数对象
 */
export const getMDFormCadecaseTreeText = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    column_name: '',
    is_filter_deleted: true,
    value: ''
  }
  Object.assign(default_options, options)
  if (Array.isArray(default_options.value)) {
    default_options.value = default_options.value.join(',')
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    post(
      '/md_form/cadecase_tree/' + default_options.id + '/' + default_options.column_name + '/text',
      default_options
    )
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              data: data.data.result.data
            })
          } else {
            resolve(null)
          }
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 根据值获取获取pop或select等的text
 * @param {object} options 参数对象
 */
export const getMDFormPopText = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    column_name: '',
    is_filter_deleted: true,
    value: ''
  }
  Object.assign(default_options, options)
  if (Array.isArray(default_options.value)) {
    default_options.value = default_options.value.join(',')
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    post(
      '/md_form/pop/' + default_options.id + '/' + default_options.column_name + '/text',
      default_options
    )
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          if (data.data.result.data) {
            resolve({
              data: data.data.result.data
            })
          } else {
            resolve(null)
          }
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
/**
 * 动态表单导出
 * @param {object} options 参数对象
 */
export const mdFormExport = function (options = {}, isloading = true) {
  const default_options = {
    id: '',
    file_name: '',
    filter_column: '',
    filter_value: '',
    summary_column: '',
    summary_filter_express: '',
    query_columns: '',
    query_column_header: '',
    fixed_filter_express: '',
    fixed_orderby_express: '',
    other_condition_express: ''
  }
  Object.assign(default_options, options)
  if (default_options.summary_filter_express) {
    if (typeof default_options.summary_filter_express === 'string') {
      default_options.summary_filter_express = Base64.encode(
        encodeURIComponent(default_options.summary_filter_express)
      )
    } else {
      default_options.summary_filter_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.summary_filter_express))
      )
    }
  }
  if (default_options.fixed_filter_express) {
    if (typeof default_options.fixed_filter_express === 'string') {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(default_options.fixed_filter_express)
      )
    } else {
      default_options.fixed_filter_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_filter_express))
      )
    }
  }
  if (default_options.fixed_orderby_express) {
    if (typeof default_options.fixed_orderby_express === 'string') {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(default_options.fixed_orderby_express)
      )
    } else {
      default_options.fixed_orderby_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.fixed_orderby_express))
      )
    }
  }
  if (default_options.other_condition_express) {
    if (typeof default_options.other_condition_express === 'string') {
      default_options.other_condition_express = Base64.encode(
        encodeURIComponent(default_options.other_condition_express)
      )
    } else {
      default_options.other_condition_express = Base64.encode(
        encodeURIComponent(JSON.stringify(default_options.other_condition_express))
      )
    }
  }
  return new Promise((resolve, reject) => {
    const ElLoading = isloading ? startLoading() : null
    post('/md_form/' + default_options.id + '/export', default_options)
      .then((data: any) => {
        if (ElLoading) ElLoading.close()
        if (data.data.result.code === 'success') {
          const content = decodeURIComponent(data.data.result.file)
          const blobContent = toBlob(content, data.data.result.filetype)
          const filename = data.data.result.filename
          if ('msSaveOrOpenBlob' in navigator) {
            // Microsoft Edge and Microsoft Internet Explorer 10-11
            const nav = window.navigator as any
            nav.msSaveOrOpenBlob(blobContent, filename)
          } else {
            // 创建隐藏的可下载链接
            const eleLink = document.createElement('a')
            eleLink.download = filename
            eleLink.style.display = 'none'
            // 字符内容转变成blob地址
            eleLink.href = URL.createObjectURL(blobContent)
            // 触发点击
            document.body.appendChild(eleLink)
            eleLink.click()
            // 然后移除
            document.body.removeChild(eleLink)
          }
          resolve(null)
        } else {
          ElMessageBox.alert('操作失败:' + data.data.result.msg, '出错了', {
            confirmButtonText: '确定'
          })
          reject(data.data.result.msg)
        }
      })
      .catch((error) => {
        if (ElLoading) ElLoading.close()
        ElMessage({
          message: error,
          type: 'error'
        })
        reject(error)
        console.error(error)
      })
  })
}
